<?php
// 应用公共文件
use app\common\model\MbtiTests;
use app\lib\qrcode\Qrcode;

function getIp($ip){
    if(!$ip){
        return '';
    }
     $ipClass = new Ip2Region();
     $select1 = $ipClass->simple($ip);
     return str_replace(["0|","中国|","|0"],'',$select1);
}

function toJson($code = 0, $msg = '', $data = [])
{
    $d['code'] = $code;
    $d['msg'] =  $msg;
    $d['data'] =  $data;
    return json($d);
}


/**
 * 计算每个维度的分
 * @param $answers
 * @param $order_no
 * @return int|string
 */
function calculateDimensionScores($answers,$order_no,$key,$password)
{

// 初始化维度得分
    $dimensions = [
        'E-I' => ['E' => 0, 'I' => 0, 'total' => 0],
        'S-N' => ['S' => 0, 'N' => 0, 'total' => 0],
        'T-F' => ['T' => 0, 'F' => 0, 'total' => 0],
        'J-P' => ['J' => 0, 'P' => 0, 'total' => 0],
    ];

// 计算得分
    foreach ($answers as $answer) {
        $dimension = $answer['dimension']; // 维度，如 E-I
        $choice = $answer['answer']; // 答案，A 或 B

        // 根据选项分配得分
        if ($choice === 'A') {
            $dimensions[$dimension][$dimension[0]] += 1; // 倾向第一个偏好（如 E）
        } else {
            $dimensions[$dimension][$dimension[2]] += 1; // 倾向第二个偏好（如 I）
        }
        $dimensions[$dimension]['total'] += 1; // 更新总分
    }
    // 计算百分比
    $percentages = [];
    foreach ($dimensions as $dimension => $scores) {
        $total = $scores['total']; // 该维度的总分
        $percentages[] = [
            $dimension[0] => bcmul(($scores[$dimension[0]] / $total),100,2) , // 第一个偏好的百分比
            $dimension[2] => bcmul(($scores[$dimension[2]] / $total),100,2), // 第二个偏好的百分比
        ];
        $netScore = $scores[$dimension[0]] - $scores[$dimension[2]]; // 净得分
        $preferences[] = ($netScore >= 0) ? $dimension[0] : $dimension[2]; // 确定偏好

    }

    $resultType = implode(',',$preferences);
    $wd['result_type'] = str_replace(',','',$resultType);
    $wd['order_no'] = $order_no;
    $wd['test_date'] = date('Y-m-d H:i:s');
    $wd['e'] = $dimensions['E-I']['E'] ;
    $wd['i'] = $dimensions['E-I']['I'];
    $wd['s'] = $dimensions['S-N']['S'];
    $wd['n'] = $dimensions['S-N']['N'];
    $wd['t'] = $dimensions['T-F']['T'];
    $wd['f'] = $dimensions['T-F']['F'];
    $wd['j'] = $dimensions['J-P']['J'];
    $wd['p'] = $dimensions['J-P']['P'];
    $wd['version'] = $key;
    $wd['password'] = $password;
    $wd['text'] = json_encode($percentages);
    $wd['ip'] = request()->ip();
    return MbtiTests::insert($wd);

}


/**
 * 获取html图片地址
 * @param string $str
 * @return string
 */
function get_img_src(string $str)
{
    $pattern = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";
    preg_match_all($pattern, $str, $match);
    return $match[1][0] ?? '';
}

/**
 * @param $str
 * @return string
 * @throws Exception
 */
function qrcode($str)
{
    return (new Qrcode())->qrcode($str);
}

function createOrderNo($length = 6)
{
    $timestamp = date("YmdHis");
    // 生成一个 4 位的随机数
    $random = str_pad(mt_rand(1, 9999), $length, '0', STR_PAD_LEFT);
    // 组合时间戳和随机数生成订单号
    return $timestamp . $random;
}

/**
 * 订单倒计时
 * @param $orderCreateTime
 * @param $orderValidDuration
 * @return array
 */
function calcDjs($orderCreateTime,$orderValidDuration)
{
    // 订单有效时长，单位为分钟
    // 计算订单过期时间
    $expirationTime = strtotime($orderCreateTime) + $orderValidDuration * 60;
    // 获取当前时间戳
    $currentTime = time();
    // 计算剩余时间（秒）
    $remainingTime = $expirationTime - $currentTime;

    if ($remainingTime > 0) {
        // 计算小时、分钟和秒
        $hours = floor($remainingTime / 3600);
        $remainingTime %= 3600;
        $minutes = floor($remainingTime / 60);
        $seconds = $remainingTime % 60;
        // 输出倒计时信息
        return [$hours,$minutes,$seconds];
    }
}